package com.example.car;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.util.Log;
import android.view.Menu;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

@SuppressWarnings("deprecation")
public class MainActivity extends TabActivity {

	JSONArray car_data = null;
	private ProgressDialog pDialog;
	JSONParser jsonParser = new JSONParser();
	String json_url = "http://api.androidhive.info/songs/albums.php";
	ArrayList<HashMap<String, String>> albumsList;
	DatabaseHandler db;
	// ALL JSON node names
	private static final String KEY_RANK				= "rank";	//NOTE: this field does not avaliable in json, just ranking of user
	private static final String KEY_NAME				= "name";
    private static final String KEY_AUTOMAKE			= "autoMake";
    private static final String KEY_AUTOMODEL			= "autoModel";
    private static final String KEY_ENGINE				= "engine";
    private static final String KEY_OBJECTTYPE			= "objectType";
    private static final String KEY_PHOTO				= "photo";
    private static final String KEY_SET					= "set";
    private static final String KEY_STATS				= "stats";
    private static final String KEY_TAGS				= "tags";
    private static final String KEY_YEAR				= "year";
    private static final String KEY_TOPSPEED			= "topSpeed";
    private static final String KEY_ACCELERATION100		= "acceleration100";
    private static final String KEY_ACCELERATION160		= "acceleration160";
    private static final String KEY_POWER				= "power";
    private static final String KEY_TORQUEFORCE			= "torqueForce";
    private static final String KEY_TORQUERPM			= "torqueRPM";
    private static final String KEY_CREDITNAME			= "creditName";
    private static final String KEY_CREDITURL			= "creditURL";
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		
		TabHost tabHost = getTabHost();
		
		// Tab for Home
        TabSpec homespec = tabHost.newTabSpec("Home");
        homespec.setIndicator("Home");//, getResources().getDrawable(R.drawable.icon_photos_tab));
        Intent homeIntent = new Intent(this, HomeActivity.class);
        homespec.setContent(homeIntent);
        
        // Tab for Cars
        TabSpec carspec = tabHost.newTabSpec("Cars");
        // setting Title and Icon for the Tab
        carspec.setIndicator("Cars");//, getResources().getDrawable(R.drawable.icon_songs_tab));
        Intent carIntent = new Intent(this, CarsActivity.class);
        carspec.setContent(carIntent);
        
        // Tab for Rankings
        TabSpec rankingspec = tabHost.newTabSpec("Rankings");
        rankingspec.setIndicator("Rankings");//, getResources().getDrawable(R.drawable.icon_videos_tab));
        Intent rankingIntent = new Intent(this, RankingsActivity.class);
        rankingspec.setContent(rankingIntent);
        
        // Tab for More
        TabSpec morespec = tabHost.newTabSpec("More");
        morespec.setIndicator("More");//, getResources().getDrawable(R.drawable.icon_videos_tab));
        Intent moreIntent = new Intent(this, MoreActivity.class);
        morespec.setContent(moreIntent);
        
        // Adding all TabSpec to TabHost
        
        tabHost.addTab(homespec);
        tabHost.addTab(carspec);
        tabHost.addTab(rankingspec);
        tabHost.addTab(morespec);
        
        db = new DatabaseHandler(this);
        Log.d("LOG: ", "execute loadJSON" );
        new LoadJSON().execute();
        
        
		
	}
	
	 class LoadJSON extends AsyncTask<String, String, String>
	 {
		 
		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			Log.d("LOG","onPreExecute");
		    super.onPreExecute();
		    pDialog = new ProgressDialog(MainActivity.this);
		    pDialog.setMessage("Loading data ...");
		            pDialog.setIndeterminate(false);
		            pDialog.setCancelable(false);
		            pDialog.show();
		        }
		
		protected String doInBackground(String... args) 
		{
			Log.d("LOG","doInBackground");
			STATIC static_var = (STATIC)getApplicationContext();
		    
	        
	        
			Log.d("LOG","before open db");
			//db.setCarRank("2010 Porsche 911 Turbo S", 10);
			int numberofCar = db.getCarsCount();
			Log.d("LOG","numberofCar = " + numberofCar);
			if(numberofCar > 0)	// already have data in SQLite, read it all
			{
				// TODO: read data from SQLite
				
				Log.d("LOG","read all car from SQLite");
				
				List<Car> allcar = db.getAllCars();
				for (Car c : allcar)
				{
				    HashMap<String, String> map = new HashMap<String, String>();
	 
					// adding each child node to HashMap key => value
					map.put(KEY_RANK, "" + c._rank);
					map.put(KEY_NAME, c._name);
					map.put(KEY_AUTOMAKE, c._automake);
					map.put(KEY_AUTOMODEL, c._automodel);
					map.put(KEY_ENGINE, c._engine);
					map.put(KEY_OBJECTTYPE, c._objecttype);
					map.put(KEY_PHOTO, c._photo);
					map.put(KEY_SET, c._set);
					map.put(KEY_STATS, c._stats);
					map.put(KEY_TAGS, c._tags);
					map.put(KEY_YEAR, c._year);
					map.put(KEY_TOPSPEED, c._topspeed);
					map.put(KEY_ACCELERATION100, c._acceleration100);
					map.put(KEY_ACCELERATION160, c._acceleration160);
					map.put(KEY_POWER, c._power);
					map.put(KEY_TORQUEFORCE, c._torqueforce);
					map.put(KEY_TORQUERPM, c._torquerpm);
					map.put(KEY_CREDITNAME, c._creditname);
					map.put(KEY_CREDITURL, c._crediturl);
					
					// adding HashList to ArrayList
					static_var.carList.add(map);
				}
				
			}
			else if(numberofCar == 0)	// The database does not have data, write it down from JSON for the first time
			{
				// getting JSON string from URL
				//List<NameValuePair> params = new ArrayList<NameValuePair>();
				//String json = jsonParser.makeHttpRequest(json_url, "POST", params);
		        
				Log.d("LOG","read all car from JSON");
				
				String json_string = ""; 
				
				// FOR TEST: Read json string from text file
		        AssetManager am = getAssets();
		        try {
					InputStream is = am.open("json-pro.json");
					InputStreamReader inputreader = new InputStreamReader(is);
					BufferedReader buffreader = new BufferedReader(inputreader);
					json_string = buffreader.readLine();
					
				} catch (IOException e) {
					e.printStackTrace();
				}
		        
		        // Check your log cat for JSON reponse
			    Log.d("LOG", "JSON > " + json_string);
			    static_var.json_respone = json_string;
				
				
				try {
					car_data = new JSONArray(json_string);
					
	                // looping through All messages
	                for (int i = 0; i < car_data.length(); i++)
	                {
	                    JSONObject c = car_data.getJSONObject(i);
	 
	                    // Storing each json item in variable
						
	                    int rank				= i + 1;	//NOTE: this field does not avaliable in json, just ranking of user
						String name				= c.getString(KEY_NAME);
						String automake			= c.getString(KEY_AUTOMAKE);
						String automodel		= c.getString(KEY_AUTOMODEL);
						String engine			= c.getString(KEY_ENGINE);
						String objecttype		= c.getString(KEY_OBJECTTYPE);
						String photo			= c.getString(KEY_PHOTO);
						String set				= c.getString(KEY_SET);
						String stats			= c.getString(KEY_STATS);
						String tags				= c.getString(KEY_TAGS);
						String year				= c.getString(KEY_YEAR);
						String topspeed			= c.getString(KEY_TOPSPEED);
						String acceleration100	= c.getString(KEY_ACCELERATION100);	
						String acceleration160	= c.getString(KEY_ACCELERATION160);	
						String power			= c.getString(KEY_POWER);
						String torqueforce		= c.getString(KEY_TORQUEFORCE);
						String torquerpm		= c.getString(KEY_TORQUERPM);
						String creditname		= c.getString(KEY_CREDITNAME);
						String crediturl		= c.getString(KEY_CREDITURL);
						
						db.addCar(new Car(
							rank,
							name,
							automake,
							automodel,
							engine,
							objecttype,
							photo,
							set,
							stats,
							tags,
							year,
							topspeed,
							acceleration100,
							acceleration160,
							power,
							torqueforce,
							torquerpm,
							creditname,
							crediturl
						) );
						
	                    // creating new HashMap
	                    HashMap<String, String> map = new HashMap<String, String>();
	 
	                    // adding each child node to HashMap key => value
	                    map.put(KEY_RANK, "" + rank);
						map.put(KEY_NAME, name);
						map.put(KEY_AUTOMAKE, automake);
						map.put(KEY_AUTOMODEL, automodel);
						map.put(KEY_ENGINE, engine);
						map.put(KEY_OBJECTTYPE, objecttype);
						map.put(KEY_PHOTO, photo);
						map.put(KEY_SET, set);
						map.put(KEY_STATS, stats);
						map.put(KEY_TAGS, tags);
						map.put(KEY_YEAR, year);
						map.put(KEY_TOPSPEED, topspeed);
						map.put(KEY_ACCELERATION100, acceleration100);
						map.put(KEY_ACCELERATION160, acceleration160);
						map.put(KEY_POWER, power);
						map.put(KEY_TORQUEFORCE, torqueforce);
						map.put(KEY_TORQUERPM, torquerpm);
						map.put(KEY_CREDITNAME, creditname);
						map.put(KEY_CREDITURL, crediturl);
						
	 
	                    // adding HashList to ArrayList
	                    static_var.carList.add(map);
	                }
	 
	            } catch (JSONException e) {
	                e.printStackTrace();
	            }
			}
			Log.d("LOG", "carList > " + static_var.carList.toString());
			
	        return null;
		}
		/**
	      * After completing background task Dismiss the progress dialog
	      * **/
		 protected void onPostExecute(String file_url) 
		 {
		     // dismiss the dialog after getting all albums
			 Log.d("LOG","onPostExecute");// + file_url);
			 pDialog.dismiss();
			 
			 
			 // updating UI from Background Thread
			 runOnUiThread(new Runnable() 
			 {
				 public void run() 
				 {
					 /**
					 * Updating parsed JSON data into ListView
					 * */
			         // TODO: update data here
					
				 }
			});

	     }
	 }
	 
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		
		return true;
	}

}
